<template>
  <div id="app">
    <Header :id="togoId" :getUrl="getUrl"></Header>
    <div class="row">
      <el-select v-model="studentIndex" filterable placeholder="请选择学生">
        <el-option
                v-for="(item,index) in bookmarkData"
                :key="item.title"
                :label="item.title"
                :value="index">
        </el-option>
      </el-select>
      <el-button type="primary" plain @click="showDialogForm('学生')">新增学生</el-button>
    </div>
    <div class="row">
      <el-select v-model="hangyeIndex" placeholder="请选择求职方向">
        <el-option
                v-for="(item,index) in hangyeBK"
                :key="item.title"
                :label="item.title"
                :value="index">
          <span style="float: left">{{ item.title }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ item.children.length }}</span>
        </el-option>
      </el-select>
      <el-button type="primary" plain @click="showDialogForm('方向')">新增方向</el-button>
    </div>
    <div class="row start">
      <el-tag type="info">收藏位置</el-tag>
      <i class="el-icon-caret-right"></i>
      <el-tag v-text="location"></el-tag>
    </div>
    <div class="dataBox">
      <el-table
              :data="jobsBK"
              style="width: 100%"
              max-height="250">
        <el-table-column
                fixed="right"
                width="50">
          <template slot-scope="scope">
            <el-button
                    @click.native.prevent="deleteRow(scope.$index)"
                    type="danger" icon="el-icon-delete" circle size="small">
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
                fixed
                width="40">
          <template slot-scope="scope">
            <img :src="scope.row.icon" alt="" style="width:100%;">
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <a href="#" @click="openBookmark(scope.row.title)" v-text="scope.row.title"></a>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :title="'新增'+dialogForm.type" :visible.sync="dialogForm.visible" width="80%">
      <el-input v-model="newBookmark.title" autocomplete="off" :disabled="newBookmark.id!==''" placeholder="请输入学生姓名" style="margin-bottom: 16px;"></el-input>
      <el-input v-for="(item,index) in newBookmark.children"
              v-model="item.title"
              autocomplete="off"
              placeholder="请输入求职方向"
              style="margin-top: 16px;">
        <template slot="prepend">{{'方向'+(index+1)}}</template>
      </el-input>
      <el-button type="primary" icon="el-icon-plus" size="mini" circle style="margin-top: 16px;" @click="addChildren()"></el-button>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogForm.visible = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Header from './components/Header.vue'

export default {
    name: 'app',
    components: {
        Header
    },
    data(){
      return{
          studentBK:[],
          hangyeBK:[],
          jobsBK: [],
          studentIndex: null,
          hangyeIndex: null,
          dialogForm:{
              visible: false,
              type: '学生'
          },
          newBookmark: {
              id: '',
              parentId: '',
              title: '',
              index: 0,
              children: [
                  {
                      id: '',
                      parentId: '',
                      title: '',
                      children: []
                  }
              ]
          },
          togoId: 0,
          location: 'togo',
          bookmarkData: []
      }
    },
    watch:{
        studentIndex(newVal,oldVal){
            this.studentIndexChange(newVal,oldVal);
        },
        hangyeIndex(newVal){
            this.hangyeIndexChange(newVal);
        }
    },
    methods:{
        studentIndexChange(newVal,oldVal){
            // 数组的深拷贝  slice(0)  contat()
            this.hangyeBK = this.bookmarkData[newVal].children.slice(0).reverse() || [];

            if(oldVal !== null){
                if(this.hangyeBK.length > 0)
                    this.hangyeIndexChange(0);
                else
                    this.hangyeIndexChange(null);
            }else{
                this.jobsBK = [];
            }
        },
        hangyeIndexChange(newVal){
            if(this.hangyeIndex !== newVal){
                this.hangyeIndex = newVal;
                return;
            }
            if(newVal !== null){
                this.hangyeBK[newVal].parentTitle = this.bookmarkData[this.studentIndex].title;
                this.localStorage({togoBookmark: this.hangyeBK[newVal]});
                this.jobsBK = this.hangyeBK[newVal].children.slice(0).reverse() || [];

                for(let i in this.jobsBK){
                    this.jobsBK[i].icon = this.matching(this.jobsBK[i].url);
                }
            }else{
                this.jobsBK = [];
            }

            this.computedLocation();
        },
        computedLocation(){
            let value = 'togo';
            if(this.studentIndex !== null){
                value += this.hangyeIndex !== null ?
                    ' — ' + this.bookmarkData[this.studentIndex].title + ' — ' + this.hangyeBK[this.hangyeIndex].title
                    : ' — ' + this.bookmarkData[this.studentIndex].title;
            }
            this.location =  value;
        },

        matching(val){
            let domain = val.split('/')[2];
            return 'https://'+domain+'/favicon.ico';
        },
        readStorage(){
            new Promise(this.getLocalStorage).then(data => {
                if(!data){
                    return;
                }

                let parentId = data.parentId;
                let id = data.id;
                for(let i in this.bookmarkData){
                    if(this.bookmarkData[i].id == parentId){
                        this.studentIndex = i - 0;
                        for(let j in this.bookmarkData[i].children){
                            if(this.bookmarkData[i].children[j].id == id){
                                this.hangyeIndex = this.bookmarkData[i].children.length - j -1;
                                return;
                            }
                        }
                    }
                }
            });
        },
        deleteRow(index) {
            let id = this.jobsBK[index].id;
            this.$confirm('此操作将永久删除该收藏, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(()=>{
                new Promise(this.removeBookmarks(id)).then(()=>{
                    this.jobsBK.splice(index, 1);
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                }).catch(() => {
                    this.$message({
                        type: 'error',
                        message: '删除失败！'
                    });
                });
            });
        },
        showDialogForm(type){
            if(type == '方向'){
                if(this.studentIndex !== null){
                    this.newBookmark.id = this.bookmarkData[this.studentIndex].id;
                    this.newBookmark.title = this.bookmarkData[this.studentIndex].title;
                    this.newBookmark.children = [{
                            id: '',
                            parentId: this.newBookmark.id,
                            title: '',
                            children: []
                        }];
                }else{
                    this.$message({
                        type: 'warning',
                        message: '请先选择学生'
                    });
                    return;
                }
            }else{
                this.newBookmark = {
                    id: '',
                    parentId: '',
                    title: '',
                    index: 0,
                    children: [
                        {
                            id: '',
                            parentId: '',
                            title: '',
                            children: []
                        }
                    ]
                };
            }

            this.newBookmark.parentId = this.togoId;
            this.dialogForm = {
                visible: true,
                type: type
            };
        },
        addChildren(){
            let lastIndex = this.newBookmark.children.length - 1;
            if(this.newBookmark.children[lastIndex].title !== ''){
                this.newBookmark.children.push({
                    id: '',
                    parentId: this.newBookmark.children[0].parentId,
                    title: '',
                    children: []
                });
            }
        },
        submit(){
            if(this.newBookmark.id !== ''){
                if(this.isHangyeRepeat()){
                    return;
                }
                this.createHangye();
            }else if(this.newBookmark.id === ''){
                if(this.isStudentRepeat()){
                    return;
                }
                this.createStudent();
            }
        },
        isStudentRepeat(){
            for(let i in this.bookmarkData){
                if(this.bookmarkData[i].title == this.newBookmark.title){
                    this.$message({
                        type: 'info',
                        message: '学生姓名重复'
                    });
                    return true;
                }
            }
            return false;
        },
        isHangyeRepeat(){
            for(let i in this.hangyeBK){
                for(let j in this.newBookmark.children){
                    if(this.hangyeBK[i].title == this.newBookmark.children[j].title){
                        this.$message({
                            type: 'info',
                            message: '行业方向重复'
                        });
                        return true;
                    }
                }
            }
            return false;
        },
        createHangye(){
            let index = this.newBookmark.index;
            if(this.newBookmark.children[index]){
                if(!this.newBookmark.children[index].title){
                    return;
                }
                let bookmark = {
                    parentId: this.newBookmark.id,
                    title: this.newBookmark.children[index].title
                };

                new Promise(this.createBookmarks(bookmark))
                    .then(result => {
                        result.children = [];
                        this.bookmarkData[this.studentIndex].children.push(result);
                        this.newBookmark.index ++;
                        this.createHangye();
                    }).catch(result => {
                        this.$message({
                            type: 'error',
                            message: '添加失败！'
                        })
                    });
            }else{
                if(this.newBookmark.index === 0){
                    this.$message({
                        type: 'info',
                        message: '至少添加一个方向'
                    })
                }else{
                    this.newBookmark.index = 0;
                    this.dialogForm.visible = false;
                    this.studentIndexChange(this.studentIndex);
                    this.$message({
                        type: 'success',
                        message: '添加成功！'
                    })
                }
            }
        },
        createStudent(){
            if(this.newBookmark.title){

                let bookmark = {
                    parentId: this.newBookmark.parentId,
                    title: this.newBookmark.title
                };

                new Promise(this.createBookmarks(bookmark))
                    .then(result => {
                        result.children = [];
                        this.bookmarkData.unshift(result);
                        this.newBookmark.id = result.id;
                        this.studentIndex = 0;
                        this.createHangye();
                    }).catch(result => {
                    this.$message({
                        type: 'error',
                        message: '添加失败！'
                    })
                });
            }else{
                this.$message({
                    type: 'info',
                    message: '请先输入学生姓名'
                })
            }
        },

        getUrl(){
            new Promise(this.getLocalStorage).then(data => {
                if(!data){
                    this.$message({
                        type: 'info',
                        message: '请先选择收藏位置'
                    });
                    return;
                }
                let that = this;
                sendMessageToContentScript({cmd:'getUrl', value:''},function (response) {
                    if(!response){return;}
                    let bookmark = {
                        parentId: data.id,
                        title: response,
                        url: response
                    };
                    new Promise(that.createBookmarks(bookmark)).then(result => {
                        that.$message({
                            type: 'success',
                            message: '添加成功'
                        });
                        result.icon = that.matching(result.url);
                        that.jobsBK.unshift(result);
                    }).catch(result => {
                        that.$message({
                            type: 'error',
                            message: '添加失败'
                        });
                    });
                })
            });
        },
        openBookmark(url){
//            sendMessageToContentScript({cmd:'open', value:url},function (response) {
//                // callback
//            })
            chrome.tabs.create({url: url}, function(tabs) {

            });
        },

        getBookmarks(resolve, reject) {
            chrome.bookmarks.getTree(function(bookmarkArray) {
                bookmarkArray = bookmarkArray[0].children[0].children;
                for (let i in bookmarkArray) {
                    if (bookmarkArray[i].title === 'TogoJoblist') {
                        resolve(bookmarkArray[i]);
                    }
                }
                reject('error');
            });
        },
        createBookmarks(bookmark){
            return (resolve, reject) => {
                chrome.bookmarks.create(bookmark, function (newFolder) {
                    resolve(newFolder);
                });
            };
        },
        removeBookmarks(id){
            return (resolve, reject) => {
                chrome.bookmarks.remove(id, function (result) {
                    resolve(result);
                });
            }
        },
        getLocalStorage(resolve, reject){
            chrome.storage.local.get(function(items) {
                resolve(items.togoBookmark);
            });
        },
        localStorage(data){
            chrome.storage.local.set(data, function(items) {

            });

            // 每次更新storage，同样要通知content去更新storage
            sendMessageToContentScript({cmd:'refresh', value:''},function (response) {
                // callback
            })
        }
    },
    mounted(){
        var pro = new Promise(this.getBookmarks);
        pro.then(result => {
            this.bookmarkData = result.children.reverse();
            this.togoId = result.id;

            this.readStorage();
            // 如果获得成功的结果，返回一个空的promise终止执行 之后的代码
            return new Promise(()=>{});
        }).catch(error => {
            return new Promise(
                this.createBookmarks({
                    parentId: '1',
                    title: 'TogoJoblist'
                })
            );
        }).then(result => {
            return new Promise(this.getBookmarks);
        }).then(result => {
            this.bookmarkData = result.children.reverse();
            this.togoId = result.id;

            this.readStorage();
        }).catch(error => {
            throw new Error('创建togo后，依旧找不到');
        });
    }
}
</script>

<style>
  #app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    width: 375px;
    min-height: 580px;
    padding-top: 50px;
    background-color: #fff;
  }
  .row{
    display: flex;
    flex-direction: row;
    margin: 10px 0;
    justify-content: space-between;
    align-items: center;
    padding: 0 16px;
  }
  .row.start{
    justify-content: flex-start;
  }
  .el-message-box{
    width: auto;
  }
  .list-box{
    padding: 8px 0;
  }
  .list{
    background-color: #fff;
    line-height: 36px;
    margin-bottom: 8px;
    font-size: 20px;
    padding-left: 16px;
    text-align: left;
  }
  .hide{
    display: none;
  }

  .el-table .cell{
    white-space: nowrap;
  }
</style>
